﻿using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.VisualStudio.XmlEditor;

namespace CodeCounsel.SharePoint.RibbonDesigner.Model
{
    public static class ExtensionManager
    {
        public static T GetReplacedChild<T>(DomainElement parent)
            where T : NamedDomainElement
        {
            T current = parent.Children.OfType<T>().FirstOrDefault();
            if (current != null)
            {
                current = GetReplacedChild<T>(parent, current);
            }
            return current;
        }

        public static T GetReplacedChild<T>(DomainElement parent, T current)
            where T : NamedDomainElement
        {
            CommandUIDefinition extension = parent.Extensions
                    .Where(e => e.Type == CommandUIExtensionType.Replace)
                    .Where(e => e.Location.Equals(current.Id))
                    .FirstOrDefault();
            if (extension != null)
            {
                current = (T)extension.Content;
            }
            return current;
        }

        public static IEnumerable<T> GetReplacedChildren<T>(DomainElement model)
          where T : NamedDomainElement
        {
            IEnumerable<T> selector = model != null ? model.Children
                .Concat(model.Extensions
                    .Where(e => e.Type == CommandUIExtensionType.Append)
                    .Select(e => e.Content))
                .OfType<T>()
                .Select(m => GetReplacedChild<T>(model, m))
                .Where(m => m != null) :
                new T[]{};
            if (typeof(T).GetInterfaces().Contains(typeof(ISequential)))
            {
                selector = selector.OrderBy(m => ((ISequential)m).Sequence);
            }
            return selector;
        }

        public static IEnumerable<T> GetChildren<T>(DomainElement model)
            where T : DomainElement
        {
            IEnumerable<T> selector = model.Children
                .Concat(model.Extensions
                    .Where(e => e.Type == CommandUIExtensionType.Append)
                    .Select(e => e.Content))
                .OfType<T>();
            if (typeof(T).IsSubclassOf(typeof(ISequential)))
            {
                selector = selector.OrderBy(m => ((ISequential)m).Sequence);
            }
            return selector;
        }
    }
}
